<template>
  <div style="margin-top: 50px">
    <el-card class="form-container" shadow="never">
    <el-steps :active="1" align-center>
      <el-step title="填写物品信息"></el-step>
      <el-step title="填写物品详实信息"></el-step>
      <el-step title="确认物品信息并提交"></el-step>
    </el-steps>
    <el-form style="margin-top: 50px" ref="form" :model="form" label-width="80px">
      <el-form-item label="物品名称" >
        <el-input v-model="goodsInfo.goodsName" placeholder="请尽量输入物品原始名称"></el-input>
      </el-form-item>
      <el-form-item label="物品类别">
        <el-select v-model="goodsOneSort" placeholder="请选择物品一级类别" @change="setGoodsOneSort">
          <el-option v-for="item in goodsSort" :label="item.title" :value="item.sortId">

          </el-option>
        </el-select>
        <el-select v-model="goodsTwoSort" placeholder="请选择物品二级类别" @change="setGoodsTwoSort">
          <el-option v-for="item in goodsSortChildren" :label="item.title" :value="item.sortId">

          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="购买时间" style="height: 50px">
        <el-col :span="6">
          <el-date-picker type="date" placeholder="选择日期" v-model="goodsInfo.goodsBuyTime" style="width: 100%;"></el-date-picker>
        </el-col>
<!--        <el-col class="line" :span="2" style="margin-left: 20px">&#45;&#45;</el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-time-picker placeholder="选择时间" v-model="form.date2" style="width: 100%;"></el-time-picker>-->
<!--        </el-col>-->
        <el-col :span="6" style="margin-left: 10px">
          <span style="color: #67C23A">(物品原始购买时间)</span>
        </el-col>
      </el-form-item>
      <el-form-item label="即时配送">
        <el-switch v-model="form.delivery"></el-switch>
      </el-form-item>
      <el-form-item label="物品品牌" >
        <el-input v-model="goodsInfo.goodsBrand" placeholder="请输入物品品牌" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="物品简介">
        <el-input
          v-model="goodsInfo.goodsText"
          :autoSize="true"
          type="textarea"
          placeholder="请输入出售闲置物品的简介。"></el-input>
      </el-form-item>
      <el-form-item label="出售价格" >
        <el-input v-model="goodsInfo.price" placeholder="请输入物品出售价格" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="物品封面">
        <el-card >
          <el-upload
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-error="handleAvatarError"
            :action="BASE_API+'/service/oss/uploadPhotoFile'"
            class="avatar-uploader">
            <img
                    v-if="goodsInfo.goodsCover" :src="goodsInfo.goodsCover"></img>
            <i  style="margin-left: 300px" v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
       </el-card>
      </el-form-item>
      <el-form-item label="物品描述">
        <div id="editor">
          <tinymce :height="400" v-model="goodsInfo.goodsText"/>
        </div>
      </el-form-item>

      <el-form-item style="text-align: center">
        <el-button type="primary" size="medium" @click="handleNext()">下一步，填写物品详实信息</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
  </div>
</template>
<style scoped>
  .form-container {
    width: 1000px;
    margin-left: 200px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
import {addOrUpdateGoods,getGoodsInfo} from '../../../api/goods/goodsInfo';
import {getGoodsSort} from '../../../api/goods/goodsSort';
import {uploadImage} from '../../../api/oss';
import Tinymce from '../../../components/Tinymce'; //引入组件

export default {

  components: { Tinymce },
        data() {
            return {
                uploadFile:undefined,
                BASE_API: process.env.BASE_API,
                form: {
                    name: '',
                    region: '',
                    date1: '',
                    date2: '',
                    delivery: false,
                    type: [],
                    resource: '',
                    desc: ''
                },
                sortValue:[],
                imageUrl: '',
                goodsInfo:{
                  goodsId:'',
                  goodsName:'',
                  goodsDesc:'',
                  goodsText:'',
                  goodsCover:'',
                  goodsSortId:'',
                  goodsBrand:'',
                  goodsBuyTime:'',
                  goodsCheck:0,
                  viewCount:0,
                  price:null,
                  version:null,
                  userId:null,
                  goodStatus:null

                },
              goodsSort:[],
              goodsOneSort:null,
              goodsTwoSort:null,
              goodsSortChildren:[]

            }
        },
      created(){
        //初始化信息
        if (this.$route.params&&this.$route.params.id){
          this.getInfo();
        }else {
          this.getGoodsSort();
        }

      },
        methods: {
          //初始化信息
          getInfo(){
            getGoodsInfo(this.$route.params.id).then(res=>{
              this.goodsInfo=res.data.goods;
            });
            //获取并匹配物品类别信息
            getGoodsSort().then(res=>{

              this.goodsSort=res.data.goodsSortList;

              //console.log(this.goodsSort)
              let isSort=false;
              for (let x of this.goodsSort) {
                   if (x.sortId===this.goodsInfo.goodsSortId){
                      this.goodsOneSort=x.sortId;
                      break;
                   }else {
                     console.log("当前的第二分类数量："+x.children.length)
                     if (x.children.length>0){
                       this.goodsSortChildren=x.children;
                       for (let x1 of x.children) {
                         console.log("当前分类的id"+x1.sortId)
                         if (x1.sortId===this.goodsInfo.goodsSortId){
                           this.goodsOneSort=x1.parentId;
                           this.goodsTwoSort=x1.sortId;
                           isSort=true;
                           break;
                         }
                       }
                     }
                   }
                   if (isSort){
                     break;
                   }
              }

            })
          },
          //初始化物品类别信息
           getGoodsSort(){
             getGoodsSort().then(res=>{

               this.goodsSort=res.data.goodsSortList;
               console.log(this.goodsSort)
             })
           },


            onSubmit() {
                console.log('submit!');
          },
          //判断是否物品有第二分类
          setGoodsOneSort(value){
             this.goodsInfo.goodsSortId=value;
            //console.log(value);
            this.goodsTwoSort=null;
            for (let x of this.goodsSort) {
              if (value===x.sortId){
                  this.goodsSortChildren=x.children;

              }
            }
            console.log('目前的goodsSortId' + this.goodsInfo.goodsSortId);
          },
          setGoodsTwoSort(value){
            this.goodsInfo.goodsSortId=value;
            console.log('目前的goodsSortId' + this.goodsInfo.goodsSortId);
          },
          //点击下一步
            handleNext(){
              this.goodsInfo.goodsBuyTime=this.dateFormat(this.goodsInfo.goodsBuyTime);
              console.log(this.goodsInfo)
              addOrUpdateGoods(this.goodsInfo).then(res=>{
                 //this.$emit('nextStep');
                //提示
                this.$message({
                  type: 'success',
                  message: '编辑物品基本信息成功!'
                });
                //跳转到第二步

                this.$router.push({path:'/goodsInfo/goodsAlbumAndVideo/'+res.data.goodsId});
              })
              // this.$emit('nextStep');
            },
          //上传成功
            handleAvatarSuccess(res, file) {
              // this.imageUrl = URL.createObjectURL(file.raw);
              // this.goodsInfo.goodsCover=URL.createObjectURL(file.raw);
              // console.log(this.goodsInfo.goodsCover);
              // console.log(res)
              // console.log(file)
              if (res.success) {
                this.goodsInfo.goodsCover = res.data.url
                console.log(this.goodsInfo.goodsCover)
                // 强制重新渲染
                this.$forceUpdate()
              } else {
                this.$message.error('上传失败(业务失败)')
              }
            },

            beforeAvatarUpload(file) {
              const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }


                return isJPG && isLt2M;
            },
          // 错误处理
          handleAvatarError() {
            console.log('error')
            this.$message.error('上传失败(http失败)')
          },
          handleChange(value){
            console.log(value)
          },
          //格式化时间
          dateFormat(date){
            let dateTime= new Date(date);
            let y=dateTime.getFullYear();
            let m=dateTime.getMonth()+1;
            let d=dateTime.getDate();
            m=m<10?('0'+m):m;
            d=d<10?('0'+d):d;
            let h=dateTime.getHours();
            let minutes=dateTime.getMinutes()
            let s=dateTime.getSeconds();
            h=h<10?('0'+h):h;
            minutes=minutes<10?('0'+minutes):minutes;
            s=s<10?('0'+s):s;
            return y+'-'+m+'-'+d+' '+h+':'+minutes+':'+s;
          }
        }
    }
</script>
